const MsgDownloader = {
  get error() { return -1; }, // 出现错误
  get fileInfo() { return 0; }, // 获取文件信息 保持与初始化一致,因为下一步就是初始化
  get download() { return 1; }, // 下载文件
  get dataIn() { return 2; }, // 数据到达
};
function CacheAudio(params) {
  this.list = [];
  if (!params.path) {
    params.path = window.location.href;
  }
  this.downloadCallback = [];
  
  this.workerDownloader = new Worker(params.path + "./js/downloader.js"); // 下载线程
  this.workerDownloader.onmessage = this.downloadMsg.bind(this);
  let i, j, t;
  for (i = 0; i < makers.length; i++) {
    makers[i].sn = i;
    if (makers[i].question.substr(0, 4) != "http") {
      makers[i].question = params.path + makers[i].question;
    }
    t = this.list.find((a) => { return a.url == makers[i].question });
    if (!t) {
      this.list.push({ e: MsgDownloader.download, i: this.list.length, url: makers[i].question });
    }
    if (Array.isArray(makers[i].answers)) {
      for (j = 0; j < makers[i].answers.length; j++) {
        if (makers[i].answers[j].audio) {
          if (makers[i].answers[j].audio.substr(0, 4) != "http") {
            makers[i].answers[j].audio = params.path + makers[i].answers[j].audio;
          }
          t = this.list.find((a) => { return a.url == makers[i].answers[j].audio });
          if (!t) {
            this.list.push({ e: MsgDownloader.download, i: this.list.length, url: makers[i].answers[j].audio });
          }
        }
      }
    }
  }
  this.download(0);
}
CacheAudio.prototype.downloadMsg = function (evt) {
  let t = 0;
  let c = 0;
  switch (evt.data.e) {
    case MsgDownloader.download:
      this.downloaded(evt.data);
      break;
    default:
      console.warn("下载线程返回其他指令:", evt.data);
      break;
  }
};
CacheAudio.prototype.download = function (i) {
  if (i >= 0 && i < this.list.length) {
    this.workerDownloader.postMessage(this.list[i]); // 发送下载命令
  } else {
    // console.log(this.list);
    for (i = 0; i < makers.length; i++) {
      t = this.list.findIndex((d) => { return d.url == makers[i].question; });
      makers[i].question = this.list[t].src;
      if (Array.isArray(makers[i].answers)) {
        for (j = 0; j < makers[i].answers.length; j++) {
          if (makers[i].answers[j].audio) {
            t = this.list.findIndex((a) => { return a.url == makers[i].answers[j].audio });
            makers[i].answers[j].audio = this.list[t].src;
          }
        }
      }
    }
    // console.log(makers);
  }
};
CacheAudio.prototype.downloaded = function (d) {
  let i, j, t;
  this.list[d.i].d = d.d;
  this.list[d.i].src = URL.createObjectURL(new Blob([this.list[d.i].d], { type: "audio/mp3" }));
  this.download(d.i + 1);
};
